from fastapi import APIRouter, Depends, HTTPException,Body
from app.schemas.user import *
from sqlalchemy.orm import Session
from ..db.session import get_db
from app.utils.security import get_current_user
from app.services.captcha import CaptchaService
from app.services.user import UserService
from ..db.models.user import User
from loguru import logger

router = APIRouter(prefix="/user", tags=["用户管理"])
@router.post("/update", summary="更新用户基本信息", response_model=UserResponse)
async def update_user(
    request_data= Body(...,
        example={
            "avatar": "http://example.com/avatar.jpg",
            "nickname": "新昵称",
            "sex": 1
        },
        description="""
        修改用户基本信息请求参数:
        - nickname: 可选，新昵称(2-20个字符)
        - sex: 可选，性别(0-女 1-男 2-保密)
        """),
    current_user: UserOut = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    if 'avatar' not in request_data or 'nickname' not in request_data or 'sex' not in request_data:
        raise HTTPException(status_code=400, detail="缺少必填字段")
    """修改昵称和性别的接口"""
    user = db.query(User).filter(User.userid == current_user.userid).first()
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    # 更新昵称
    if 'nickname' in request_data and request_data['nickname']:
        if len(request_data['nickname']) < 2 or len(request_data['nickname']) > 20:
            raise HTTPException(status_code=400, detail="昵称长度必须在2-20个字符之间")
        user.nickname = request_data['nickname']
    
    # 更新性别
    if 'sex' in request_data and request_data['sex'] is not None:
        if request_data['sex'] not in [0, 1, 2]:
            raise HTTPException(status_code=400, detail="性别参数不合法")
        user.sex = request_data['sex']
    
    db.commit()
    db.refresh(user)
    
    return {
        'code': 0,
        'message': '成功',
        'data': None
    }

@router.get("/update/email/captcha", summary="获取邮箱修改验证码")
async def get_email_captcha(email:str):
    """发送验证码到对应邮箱"""
    captcha = CaptchaService.generate_captcha(email)
    logger.debug(f"[开发环境] 登录验证码: {captcha}")  # 开发环境直接打印
    return {
        "code":200,
        "message": "验证码已发送"
        }

@router.post("/update/email", summary="提交邮箱修改", response_model=UserResponse)
async def update_email(
    request_data= Body(...,
        example={
            "originalEmail": "old@example",
            "newEmail": "new@example.com",
            "captcha": "123456"
        },
        description="""
        修改邮箱请求参数:
        - originalEmail: 必填，原邮箱地址
        - newEmail: 必填，新的邮箱地址
        - captcha: 必填，6位数字验证码
        """),
    current_user: UserOut = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    if not CaptchaService.verify_captcha(request_data["newEmail"], request_data["captcha"]):
        raise HTTPException(status_code=400, detail="验证码错误或已过期")
    if UserService.get_user_by_email(db, request_data["newEmail"]):
        raise HTTPException(status_code=400, detail="邮箱已被存在")
    user = db.query(User).filter(User.userid == current_user.userid).first()
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    user.email = request_data["newEmail"]
    db.commit()
    db.refresh(user)
    return {
        'code': 200,
        "message": "邮箱修改成功",
        'data': current_user.model_dump()
    }
@router.get("/search", summary="用户搜索功能")
async def search_user(
    keyword: str,
    current: int = 1,
    size: int = 20,
    db: Session = Depends(get_db)
):
    """
    用户搜索接口
    参数:
    - keyword: 搜索关键词(昵称)
    - current: 当前页码(从1开始)
    - size: 每页数量
    
    返回分页的用户列表
    """
    offset = (current - 1) * size
    total = db.query(User).filter(
        User.nickname.ilike(f"%{keyword}%")
    ).count()
    # 计算总页数
    pages = (total + size - 1) // size
     # 查询当前页的用户列表
    users = db.query(User).filter(
        User.nickname.ilike(f"%{keyword}%")
    ).offset(offset).limit(size).all()
    # 构建响应数据
    user_list = [
        {
            "id": user.id,
            "userid": user.userid,
            "nickname": user.nickname,
            "avatar": user.avatar,
            "sex": user.sex,
            "online": 1 if user.online else 0
        }
        for user in users
    ]
    return {
        "code": 0,
        "message": "成功！",
        "data": {
            "total": total,
            "pages": pages,
            "list": user_list,
            "requestId": None
        }
    }

@router.get("/info", response_model=UserResponse, summary="获取用户详细信息")
async def get_user_info(
    userid: str = None,  # 通过业务ID查询
    id: int = None,      # 通过数字主键查询
    db: Session = Depends(get_db)
):
    """
    获取用户详细信息
    返回示例：
    ```json
    {
        "code": 200,
        "data": {
            "id": 123,
            "userid": "uuid-xxx",
            "email": "user@example.com",
            "nickname": "张三",
            "avatar": "http://example.com/avatar.jpg",
            "sex": 1,
            "online": true,
            "created_at": "2023-01-01T00:00:00",
            "last_at": "2023-01-02T12:00:00"
        }
    }
    ```
    """
    if not userid and not id:
        raise HTTPException(status_code=400, detail="必须提供userid或id参数")
    
    # 通过服务层获取用户信息
    user = None
    if userid:
        user = UserService.get_user_by_userid(db, userid)
    else:
        user = UserService.get_user_by_id(db, id)
    
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    # 使用UserOut模型格式化返回数据
    targetUser = UserOut.model_validate(user)
    
    return {
        "code": 200,
        "message": "获取用户信息成功",
        "data": targetUser.model_dump()
    }